package com.yyq.adms.yyb.advance.action;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.map.LinkedMap;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.yyq.adms.util.JxlsUtil;
import com.yyq.adms.util.JxlsVo;
import com.yyq.adms.util.ValidateUtil;
import com.yyq.adms.util.ValidateVo;
import com.yyq.adms.yyb.advance.bpo.STApplyBpo;
import com.yyq.adms.yyb.advance.bpo.STPaperBpo;
import com.yyq.adms.yyb.advance.pojo.STApply;
import com.yyq.adms.yyb.advance.pojo.STPaper;
import com.yyq.adms.yyb.paper.pojo.PaperSubmission;
import com.yyq.adms.yyb.paper.pojo.PublishPaper;
import com.yyq.adms.yyb.utils.YYBUtils;
import com.yyq.sos.action.BaseAction;
import com.yyq.sos.constants.ActionType;
import com.yyq.sos.constants.Constants;
import com.yyq.sos.permission.LoginUser;
import com.yyq.sos.util.PermissionsUtil;
import com.yyq.sos.util.page.PageFormData;

/**
 * 科技进步 奖励申报
 * @author 杨应滨
 * @2012-12-7
 *
 */
@Controller("STApplyAction")
@Scope("prototype")
public class STApplyAction extends BaseAction{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private STApply po = new STApply();
	
	private STApplyBpo bpo;
	
	private STPaperBpo paperBpo;
	
	public STPaperBpo getPaperBpo() {
		return paperBpo;
	}
	@Resource(name="STPaperBpo")
	public void setPaperBpo(STPaperBpo paperBpo) {
		paperBpo.setCls(STApply.class);
		this.paperBpo = paperBpo;
	}

	public STApply getPo() {
		return po;
	}

	public void setPo(STApply po) {
		this.po = po;
	}

	public STApplyBpo getBpo() {
		return bpo;
	}

	@Resource(name="STApplyBpo")
	public void setBpo(STApplyBpo bpo) {
		bpo.setCls(po.getClass());
		this.bpo = bpo;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}
	
	public String execute()throws Exception
	{
		super.setBpo(bpo);
		super.setObj(po);
		String s = super.execute();
		this.setPo((STApply)super.getObj());
		return s;
	}
	
	
	@Override
	public String data() {

		LoginUser user = (LoginUser)this.getSession().getAttribute(Constants.LOGIN_USER);
		String moduleName = getModuleName(this.getRequest().getRequestURI());
		boolean isPerm = PermissionsUtil.checkPermissionByCode(this.getSession(), moduleName,Constants.RIGHT_GLOBAL);
		String hql = "";
		if(user.getUserId().intValue()==1 || isPerm){
			hql = "from STApply order by applyDate desc";
		}else{
			hql = "from "+po.getClass().getName()+" obj where obj.maintainDep="+user.getOrgId()+" or EXISTS(from RecordSentDep rsd where obj.id=rsd.sourceRecordId and rsd.yyqTableName='"+bpo.getTableName(po.getClass())+"' and rsd.sentDepId="+user.getOrgId()+")  order by obj.applyDate desc";
		}
		this.setFormData(bpo.searchPage(hql, getPageForm().getPageNo(), getPageForm().getPageSize()));
		
		processData();
		
		return ActionType.ACTION_DATA_LIST;
	}

	private void processData() {
		PageFormData formData= this.getFormData();
		List _templist = formData.getData();
		List _list = new ArrayList();
		for(int i = 0; i < _templist.size(); i ++) {
			STApply _declare = (STApply)_templist.get(i);
			Date _date = _declare.getApplyDate();
			String _year = YYBUtils.getFormatDateYear(_date);
			_declare.setBelongYear(_year);
			_list.add(_declare);
		}
		if(_list.size() > 0) 
			formData.setData(_list);
	}
	

	public String search()
	{
		String searchProperty = ((String[])this.getFormValue("searchProperty"))[0];
		String searchKey = ((String[])this.getFormValue("searchKey"))[0];
		LoginUser user = (LoginUser)this.getSession().getAttribute(Constants.LOGIN_USER);
		String moduleName = getModuleName(this.getRequest().getRequestURI());
		boolean isPerm = PermissionsUtil.checkPermissionByCode(this.getSession(), moduleName,Constants.RIGHT_GLOBAL);
		String hql = "";
		if(user.getUserId().intValue()==1 || isPerm){
			if("sentDep".equals(searchProperty)){
				hql = "select distinct obj from "+po.getClass().getName()+" obj,RecordSentDep rsd,SysDepts d where " +
					  " obj.id=rsd.sourceRecordId and rsd.sentDepId=d.id and rsd.yyqTableName='"+bpo.getTableName(po.getClass())+"' and d.deptCname like '%"+searchKey+"%' order by applyDate desc";
			}else{
				hql = "from "+po.getClass().getName()+" where "+searchProperty+" like '%"+searchKey+"%' order by applyDate desc";
			}
		}else{
			hql = "from "+po.getClass().getName()+" obj where (obj.maintainDep="+user.getOrgId()+" or EXISTS(from RecordSentDep rsd where obj.id=rsd.sourceRecordId and rsd.yyqTableName='"+bpo.getTableName(po.getClass())+"' and rsd.sentDepId="+user.getOrgId()+")) and obj."+searchProperty+" like '%"+searchKey+"%' order by obj.applyDate desc";
		}
		this.setFormData(bpo.searchPage(hql, this.getPageForm().getPageNo(), this.getPageForm().getPageSize()));
		processData();
		return ActionType.ACTION_DATA_LIST;
	}
	
	@Override
	public String batchAdd() {
		if(this.getAccessory() != null){
			String msg = "";
			if("xls".equals(this.getAccessoryFileName().substring(this.getAccessoryFileName().lastIndexOf(".")+1))){
				try {
					List<Map<String, JxlsVo>> srcData = JxlsUtil.getInstance().transfromData(this.getAccessory(),3);
					List<STApply> targetData = new ArrayList<STApply>();
					LoginUser user = (LoginUser)this.getSession().getAttribute(Constants.LOGIN_USER);
					List<Map<String, JxlsVo>> otherOrgRepeatData = new ArrayList<Map<String, JxlsVo>>(); 
					Map<String,Object> vMap = new LinkedHashMap<String, Object>();
					msg = bpo.validateBatchAdd(srcData, targetData,vMap,user,otherOrgRepeatData);
					if(msg.toString().equals("") && otherOrgRepeatData.size()==0){
						if(targetData.size()>0){
							Serializable[] ids = bpo.save(targetData.toArray());
							if(ids != null){
								List sds = new ArrayList();
								String tableName = bpo.getTableName(po.getClass());
								for(int i=0;i<targetData.size();i++){
									 STApply o = targetData.get(i);
									String v = o.getSentDep();
									Object objId = o.getId();
									processSentDep(sds, tableName, v, objId);
								}
								msg = "{processId:\"1\",msg:\"批量导入成功!\"}";
								if(sds.size()>0){
									ids = bpo.save(sds.toArray());
									if(ids == null){
										msg = "{processId:\"1\",msg:\"批量导入成功,报送单位添加失败!\"}";
									}
								}
							}else{
								msg = "{processId:\"1\",msg:\"批量导入失败!\"}";
							}
						}else{
							msg = "{processId:\"1\",msg:\"批量添加数据为空,请添加数据!\"}";
						}
					}else{
						this.getSession().setAttribute("msg", msg);
						this.getSession().setAttribute("vMap", vMap);
						this.getSession().setAttribute("repeatData", otherOrgRepeatData);
						this.getSession().setAttribute("repeatKey", "项目名称+申报年度");
						msg = "{processId:\"3\",msg:\"数据重复!\",width:\""+vMap.size()+"\",height:\""+otherOrgRepeatData.size()+"\"}";
					}
				} catch (Exception e) {
					msg = "{processId:\"1\",msg:\"批量导入出错!\"}";
					e.printStackTrace();
				}
				this.setMsg(msg);
			}else{
				this.setMsg("{processId:\"1\",msg:\"文件类型不支持!\"}");
			}
		}
		return ActionType.ACTION_MSG;
	}
	
	public String goAdd()
	{
		String[] type = (String[])this.getFormValue("type");
		if(type != null && "publish".equals(type[0])){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			this.setFormValue("nowDate", sdf.format(new Date()));
			String sentDep = po.getSentDep();
			po = (STApply)bpo.findByPk(po.getId());
			po.setSentDep(sentDep);
			this.setObj(po);
			return "publishAdd";
		}else{
			return ActionType.ACTION_GO_ADD;
		}
	}
	
	@Override
	public String update() {
		// TODO Auto-generated method stub
		String state = this.po.getJudgeState();
		Long sourceID = this.po.getId();
		String result =  super.update();
		String updateFlag = (String)this.getFormValue("updateFlag");
		if(state!=null && state.equals("表彰")&& "TRUE".equals(updateFlag)) {
			// 已发表 需保存
			String tableName = paperBpo.getTableName(PublishPaper.class);
			List _tempList = paperBpo.searchSql("select * from " + tableName + " where sourceid = " + sourceID);
			
			if(_tempList.size() == 0 ) {
				this.setMsg("{processId:\"2\",msg:\"更新成功\",sourceId:\""+sourceID+"\",sentDep:\""+po.getSentDep()+"\"}");
				
				/*STPaper target = new STPaper();
				target.setProjectName(po.getProjectName());
				target.setPaperLevel(po.getApplyLevel());
				target.setJudgeCorporation(po.getJudgeCorporation());
				target.setBelongPlateFormID(po.getBelongPlateFormID());
				target.setPaperPerson(po.getDepartment());
				target.setFinishedDep(po.getProjectFinishName());
//				target.setSentDep(po.getSentDep());
				target.setSourceID(sourceID.intValue());
				Serializable id = paperBpo.save(target);
				if(id != null){
					String sentDep = po.getSentDep();
					List sds = new ArrayList();
					processSentDep(sds, tableName, sentDep, id);
					if(sds.size()>0){
						Serializable[] ids = bpo.save(sds.toArray());
					}
				}*/
				
			}
		}
		return result;
	}
	
	
	
	
	
	
	
	

}
